package com.ct.controller.login;

import com.ct.commons.annotation.HasPermissionApi;
import com.ct.commons.annotation.LoginIgnore;
import com.ct.utils.HttpClientUtils;
import com.ct.utils.exception.BusinessException;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 1 手机登陆  绑定微信  button
 * 2 微信登陆  绑定手机  验证码
 * <p>
 * 微信扫码登录api
 */
@CrossOrigin
@Controller
@Log4j2
@LoginIgnore
public class WxApiController{

    @GetMapping("/vadmin/weilogin/callback")
    @HasPermissionApi
    public String callback(String code, String state, HttpServletResponse response, HttpServletRequest request) {
        response.setHeader("Set-Cookie", "SameSite=None; Secure");
        // 1：判断code是否合法
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("CODE_EMPTY","code不能为空");
        }
        // 2：通过code获取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(baseAccessTokenUrl,"wx5c890ee944ed7cef", "c35dd8e0401f6d681fee2eddd35ab8e3", code);
        String result = null;
        try {
            //2：执行请求，获取微信请求返回得数据
            result = new HttpClientUtils().get(accessTokenUrl);
            log.info("2---->微信返回的日志信息是：code:{},result：{}", code, result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("22007", "登录失败，尝试刷新重新扫码登录!");
        }


        // 3： 对微信返回得数据进行转换
        Gson gson = new Gson();
        Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);
        log.info("3---->微信返回的日志信息是：code:{}，resultMap：{}", code, resultMap);

        // 4: 解析微信用户得唯一凭证openid
        String accessToken = (String) resultMap.get("access_token");
        String openid = (String) resultMap.get("openid");
        if (StringUtils.isEmpty(openid)) {
            throw new BusinessException("22007", "登录失败，尝试刷新重新扫码登录!");
        }

        if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openid)) {
            throw new BusinessException("22007", "登录失败，尝试刷新重新扫码登录!");
        }

        String sid = request.getParameter("sid");

        // 10:重定向中转页面
        // 弹窗登录
        return "redirect:http://www.kaiheng.top//adduser?openid="+openid+"&sid="+sid;
    }
}